package com.mall.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.common.dto.SkuHasStockDTO;
import com.common.dto.SkuReductionDTO;
import com.common.utils.R;
import com.mall.ware.entity.PurchaseDetailEntity;
import com.mall.ware.exception.NoStackException;
import com.mall.ware.feign.ProductFeign;
import com.mall.ware.vo.OrderItemVo;
import com.mall.ware.vo.WareSkuLockVo;
import com.mall.ware.vo.result.LockStockResult;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mall.ware.dao.WareSkuDao;
import com.mall.ware.entity.WareSkuEntity;
import com.mall.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private WareSkuDao wareSkuDao;
    @Autowired
    private ProductFeign productFeign;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String  skuId = (String)params.get("skuId");
        String wareId = (String)params.get("wareId");
        if (StringUtils.isNotEmpty(skuId)){
            wrapper.eq("sku_id",skuId);
        }
        if (StringUtils.isNotEmpty(wareId)){
            wrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(PurchaseDetailEntity detailServiceById) {
        Long skuId = detailServiceById.getSkuId();
        Long wareId = detailServiceById.getWareId();
        Integer skuNum = detailServiceById.getSkuNum();
        List<WareSkuEntity> list = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>()
                .eq("sku_id", skuId)
                .eq("ware_id", wareId));
        if (ObjectUtil.isNull(list)){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            try {
                R info = productFeign.info(skuId);
                Map<String,Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0){
                    wareSkuEntity.setSkuName((String)skuInfo.get("skuName"));
                }
            } catch (Exception e) {

            }
            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuNum,wareId,skuId);
        }
    }

    /**
     * 获取每个skuID对应的库存
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockDTO> getSpuHasStock(List<Long> skuIds) {
        List<SkuHasStockDTO> list = skuIds.stream().map(skuId -> {
            Long count = baseMapper.getSkuStock(skuId);
            SkuHasStockDTO dto = new SkuHasStockDTO();
            dto.setSkuId(skuId);
            dto.setHasStock(count > 0);
            return dto;
        }).collect(Collectors.toList());
        return list;
    }

    @Override
    public Boolean orderLockStack(WareSkuLockVo vo) {
        List<OrderItemVo> items = vo.getItems();
        List<SkuWareHasStack> hasStacks = items.stream().map(item -> {
            SkuWareHasStack skuWareHasStack = new SkuWareHasStack();
            List<WareSkuEntity> wareSkuEntities = this.baseMapper.listHasStock(item.getSkuId());
            skuWareHasStack.setWareIds(wareSkuEntities);
            skuWareHasStack.setNum(item.getCount());
            return skuWareHasStack;
        }).collect(Collectors.toList());
        for (SkuWareHasStack hasStack : hasStacks) {
            Long skuId = hasStack.getSkuId();
            List<WareSkuEntity> skuEntityList = hasStack.getWareIds();
            if (ObjectUtil.isNull(skuEntityList)){
                String skuName = vo.getItems().get(skuId.intValue()).getTitle();
                throw new NoStackException(skuName);
            }
           Integer num = hasStack.getNum();
            Boolean hasStacked = false;
            for (WareSkuEntity skuEntity : skuEntityList) {
                Integer canStack = skuEntity.getStock() - skuEntity.getStockLocked();
                if (num <= canStack){
                    Integer count = this.baseMapper.lockSkuStack(skuId,skuEntity.getWareId(),num);
                    num = 0;
                    hasStacked = true;
                }else {
                    Integer count = this.baseMapper.lockSkuStack(skuId,skuEntity.getWareId(),num);
                    num = num - canStack;
                }
                if (num <= 0){
                    break;
                }
            }
            if (!hasStacked){
                throw new NoStackException(skuEntityList.get(skuId.intValue()).getSkuName());
            }
        }
        return true;
    }
    @Data
    class SkuWareHasStack{
        private Long skuId;
        private Integer num;
        private List<WareSkuEntity> wareIds;
    }
}